//
//  CSNetworkHelper.m
//  CreateWithSuper
//
//  Created by chenjunbo on 2024/6/15.
//  Copyright © 2024 CS. All rights reserved.
//

#import "CSNetworkHelper.h"
#import <AFNetworking/AFNetworking.h>
#import "CSCryptionTool.h"
#import "MJExtension.h"
#import "SVProgressHUD.h"
#import "CSKey.h"
#import "ADModule.h"

@interface CSNetworkHelper()

@property (strong,nonatomic) AFHTTPSessionManager *manager;

@end

@implementation CSNetworkHelper

const NSString * bidStr = @"com.wulacode.aipainter";

+ (instancetype)standardInstance {
    static CSNetworkHelper *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.manager = [AFHTTPSessionManager manager];
        self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        AFSecurityPolicy *securityPolicy =  [AFSecurityPolicy defaultPolicy];
        securityPolicy.allowInvalidCertificates = YES;
        securityPolicy.validatesDomainName = NO;
        self.manager.securityPolicy = securityPolicy;
    }
    return self;
}

- (NSMutableDictionary *)configRequestDict{
    NSMutableDictionary *requestDict = [[NSMutableDictionary alloc]init];
    
    UIDevice *device = [UIDevice currentDevice];
    NSString *systemVersion = [device systemVersion];
    
    NSString *countryCode = nil;
    NSLocale *locale = [NSLocale currentLocale];
    countryCode = [locale objectForKey:NSLocaleCountryCode];

    NSBundle *bundle = [NSBundle mainBundle];
    
    requestDict[@"aid"] = [CSKey getKey];
    requestDict[@"country"] = countryCode;
    requestDict[@"lang"] = [locale objectForKey:NSLocaleLanguageCode];
    requestDict[@"packageName"] = @"com.wulacode.aipainternolimit";
    requestDict[@"plmn"] = @"";
    requestDict[@"sdk"] = [systemVersion substringToIndex:2];
    requestDict[@"ver"] = @(1);
    
    NSLog(@"%@",requestDict);
    
    return requestDict;
}

- (NSData *)appendRequestDataWithDict:(NSMutableDictionary *)requestDict{
    
    NSString *dictStr = [requestDict mj_JSONString];

    const unsigned char *bidbytes = (const unsigned char *)[[bidStr dataUsingEncoding:NSUTF8StringEncoding] bytes];
    const unsigned char *bytes = (const unsigned char *)[[dictStr dataUsingEncoding:NSUTF8StringEncoding] bytes];
        
    NSMutableArray *byteArr = [NSMutableArray array];
    
    [byteArr addObject:@(bidStr.length)];
    
    for (int i = 0; i < [[bidStr dataUsingEncoding:NSUTF8StringEncoding] length]; i++) {
        [byteArr addObject:@(bidbytes[i])];
    }
    
    for (int i = 0; i < [[dictStr dataUsingEncoding:NSUTF8StringEncoding] length]; i++) {
        [byteArr addObject:@(bytes[i])];
    }

    // 存储字节
    NSMutableData *data = [NSMutableData data];
     
    // 遍历数组，将每个NSNumber转换为字节，并追加到NSMutableData对象中
    for (NSNumber *number in byteArr) {
        // 获取数值的字节表示，这里假设是32位整数
        uint8_t byteValue = [number intValue];
        // 将字节追加到NSMutableData对象中
        [data appendBytes:&byteValue length:sizeof(byteValue)];
    }
    // 现在data包含了原OC数组转换成的字节数据
    uint8_t *useBytes = (uint8_t *)[data bytes];
 
    // 转换为NSData
    NSData *requestData = [[NSData alloc] initWithBytes:useBytes length:byteArr.count];
    return requestData;
}

- (void)requestWithUrl:(NSString *)url requestDict:(NSMutableDictionary *)requestDict{
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    
    NSError *error;
    NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestDict options:0 error:&error];

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:requestData];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSURLSessionTask *sessionTask = [self.manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        NSLog(@"%@",requestDict);
        NSLog(@"%@",dictionary);
    }];
    
    [sessionTask resume];
}

- (void)requestWithUrl:(NSString *)url requestDict:(NSMutableDictionary *)requestDict
     completionHandler:(nullable void (^)(id _Nullable responseObject))completionHandler{
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    NSData *requestData = [self appendRequestDataWithDict:requestDict];
    NSData *encryptData = [CSCryptionTool encryptData:requestData k:@"Vf475GhmTgfTf6Nj" v:@"PN4G3hhHWds43vNf"];

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:encryptData];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSURLSessionTask *sessionTask = [self.manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        NSData *data = [CSCryptionTool decryptData:responseObject k:@"Af356hmTgfTf563E" v:@"PN4G3hhHWds43vNf"];
        
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

        if (!dictionary) {
            completionHandler ? completionHandler(nil) : nil;
        } else {
            
            if (dictionary[@"code"]) {
                int code = [dictionary[@"code"]intValue];
                if (code == 200){
                    completionHandler ? completionHandler(dictionary) : nil;
                }else{
                    completionHandler ? completionHandler(nil) : nil;
                }
            } else {
                completionHandler ? completionHandler(dictionary) : nil;
            }
            

            
        }


    }];
    
    [sessionTask resume];
}

- (void)requestVps{
    [self requestWithUrl:@"http://qrscanonetool.com/app/vps" requestDict:[self configRequestDict] completionHandler:^(NSDictionary * responseObject) {
        
        NSLog(@"网络请求http://qrscanonetool.com/app/vps : \n%@",responseObject);

        if (responseObject){
            NSArray *dictArr = responseObject[@"data"];
            
            if (dictArr && dictArr.count > 0) {
                NSInteger randomIndex = arc4random_uniform(dictArr.count);
                NSDictionary *dict = dictArr[randomIndex];
                
//                [CSVpnManager standardInstance].currentData = dict;
                
            }
        }else{

            NSString *filePath = [[NSBundle mainBundle] pathForResource:@"ser" ofType:@"json"];

            NSData *data = [NSData dataWithContentsOfFile:filePath];
            NSError *error = nil;
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

            if (!error) {

                NSArray *dictArr = json[@"data"];
                
                if (dictArr && dictArr.count > 0) {
                    NSInteger randomIndex = arc4random_uniform(dictArr.count);
                    NSDictionary *dict = dictArr[randomIndex];
                    
//                    [CSVpnManager standardInstance].currentData = dict;
                    
                }
            }
        }

        
    }];
}

- (void)postMoneyWithURL:(NSString *)url CurrentIp:(NSString *)ip adid:(NSString *)adid adformat:(NSString *)format valueMicros:(double)micros currencyCode:(NSString *)currency precisionType:(int)precision{
    
    NSMutableDictionary *requestDict = [[NSMutableDictionary alloc]initWithDictionary:[self configRequestDict]];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    
    dict[@"ip"] = ip;
    dict[@"adId"] = adid;
    dict[@"adFormat"] = [format mj_JSONString];
    dict[@"adPlatform"] = [@"admob" mj_JSONString];
    dict[@"valueMicros"] = @(micros);
    dict[@"currencyCode"] = [currency mj_JSONString];
    dict[@"precisionType"] = @(precision);

    requestDict[@"adValue"] = dict;

    [self requestWithUrl:url requestDict:requestDict];
    
}

- (void)requestAiDefault{
    [self requestWithUrl:@"http://qrscanonetool.com/app/aiDefault" requestDict:[self configRequestDict] completionHandler:^(id  _Nullable responseObject) {

        NSLog(@"网络请求http://qrscanonetool.com/app/aiDefault: \n%@",responseObject);




    }];
}

- (void)requestConfiguration{
    [self requestWithUrl:@"http://qrscanonetool.com/app/configuration" requestDict:[self configRequestDict] completionHandler:^(id  _Nullable responseObject) {

        NSLog(@"网络请求http://qrscanonetool.com/app/configuration: \n%@",responseObject);
        
        if (responseObject){
            [ADModule standardInstance].dataDict = responseObject[@"data"];
            [ADModule standardInstance].wordshow = [responseObject[@"data"][@"wordshow"] intValue];
            [[ADModule standardInstance]requestAllAd];
        }else{
            NSString *filePath = [[NSBundle mainBundle] pathForResource:@"config" ofType:@"json"];

            NSData *data = [NSData dataWithContentsOfFile:filePath];
            NSError *error = nil;
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

            if (!error) {
                [ADModule standardInstance].dataDict = json[@"data"];
                [[ADModule standardInstance]requestAllAd];
            }

        }



    }];
}

- (void)requestTxt2img:(NSString *)text callback:(void (^)(NSString * result))callback{
    
    NSMutableDictionary *requestDict = [NSMutableDictionary dictionaryWithDictionary:[self configRequestDict]];
    
    requestDict[@"text"] = text;
    
    [SVProgressHUD showWithStatus:@"Loading"];

    
    [self requestWithUrl:@"http://qrscanonetool.com/app/txt2img" requestDict:requestDict completionHandler:^(id  _Nullable responseObject) {
        
        NSLog(@"%@",responseObject);
//
        
        if (responseObject[@"task_id"]){
            [SVProgressHUD dismiss];
            callback(responseObject[@"task_id"]);
        }else{
            [SVProgressHUD showErrorWithStatus:@"Try again"];
            dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC));
            dispatch_after(delay, dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }

    }];
    
}

- (void)requestTaskRequest:(NSString *)taskId callback:(void (^)(id result))callback{
    
    NSMutableDictionary *requestDict = [NSMutableDictionary dictionaryWithDictionary:[self configRequestDict]];
    
    requestDict[@"taskId"] = taskId;
    
    [self requestWithUrl:@"http://qrscanonetool.com/app/task-result" requestDict:requestDict completionHandler:^(id  _Nullable responseObject) {
        
        callback(responseObject);
    
    }];
}

@end
